
package com.scalar.chiptrack.alarms.actions;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionForm;

import com.scalar.ScalarException;
import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.commons.Constants;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.utils.ConfigManager;
import com.scalar.chiptrack.users.User;

import com.scalar.chiptrack.alarms.Alarm;
import com.scalar.chiptrack.alarms.dao.AlarmDAO;


public class AlarmsWarningsAction extends ChipTrackAction {

    private static String SOURCE_PAGE = "/alarmsWarnings.do";

    public ActionForward execute (ActionMapping mapping,
                                  ActionForm form,
                                  HttpServletRequest request,
                                  HttpServletResponse response) 
                                  throws Exception {
                                      
        User user = null;
        HttpSession session = request.getSession();
        
        String action = request.getParameter ("action");
        
        if (action == null) 
        {
            action = (String) session.getAttribute ("alarmAction");
        }
        
        if ((user = (User) session.getAttribute (SessionKeys.USER_KEY)) == null) 
        {
            String forwardPage = ConfigManager.getDefaultLoginPage() + "?sourcePage=" + SOURCE_PAGE;
            if ("show".equalsIgnoreCase(action) == true) 
            {
                String alarmId = request.getParameter ("alarmId");
                if ((alarmId != null) && (alarmId.trim().length() != 0)) 
                {
                    session.setAttribute ("alarmAction", "show");
                    session.setAttribute ("alarmId", alarmId);
                }
            }
            
            return new ActionForward (forwardPage);
        }

        
        if ("show".equalsIgnoreCase (action)) 
        {
            int alarmId = -1;
            try {
                alarmId = Integer.parseInt (request.getParameter ("alarmId"));
            }
            catch (NumberFormatException nfe) {
                try { alarmId = Integer.parseInt ((String)session.getAttribute("alarmId")); } catch (NumberFormatException ignore) {}
            }
            
            // for now show default Alarm details page
            // later, send it to particular module for the details
            Alarm alarm = AlarmDAO.loadAlarmById (alarmId);
            
            /* this is added by ravikanth on 28 July 03 to
             *  show sales_order notification on a JSP
             */ 
                                         
			// this redirects to another action class if alarm type is SALES_ORDER
			                                          
            if( alarm.getType().equals( Constants.SALES_ORDER_ALARM ) || alarm.getType().equals( Constants.SAMPLE_ORDER_ALARM ))
            {
            	request.setAttribute("alarmObj",alarm);
            	return mapping.findForward("sales_order");
            }
            
            //changes made by ravikanth  Upto this point

            /**
			 *	added by gandhi on 04-Jun-04 3pm to show
			 *	quote notification details by redirecting to
			 *	QuotationNotificationShowAction.java if alarm type is QUOTE
			*/

             if(alarm.getType().equals(Constants.QUOTE_ALARM))
            {
            	request.setAttribute("alarmObj",alarm);
            	return mapping.findForward("quotation");
            }

            //  end of changes made by gandhi

            request.setAttribute ("alarmInfo", alarm.toHTML());
            return (mapping.findForward ("alarmInfo"));
	    }
        else if ("confirm".equalsIgnoreCase (action)) 
        {
        	Enumeration params = request.getParameterNames();
			ArrayList alarmIds = new ArrayList(100);
			String name = null;
			HashMap alarmMap = null;
			String alarmId = null;
			HashMap error = new HashMap();
			
			while (params.hasMoreElements()) 
			{
				name = (String) params.nextElement();
    			if ( name.startsWith ("select_") ) 
    			{
    				String[] alarmValues = request.getParameterValues(name);
    				for( int i=0; i < alarmValues.length; i++ )
    				{ 
						alarmIds.add(alarmValues[i]);
    				}
				}
			}
			
			try
			{
				alarmMap = AlarmDAO.loadAlarmByIdList(alarmIds.iterator());
			}
			catch (ScalarException se) 
			{
				 se.getRootCause().printStackTrace();
			}
			request.setAttribute("alarmMap",alarmMap);
							 
			
			error.put ("Are you sure,you want to remove", null);
			request.setAttribute (SessionKeys.ERROR_MESSAGES, error);
			return (mapping.findForward ("alarmConfirm"));
					 
        }
		else if ( "remove".equalsIgnoreCase (action) ) 
		{
			String[] alarmIds = request.getParameterValues("alarmIds");
			HashMap errors = new HashMap();
			HashMap info = new HashMap();
			for( int i=0; i<alarmIds.length ; i++ ) 
			{
				try 
        		{
					AlarmDAO.removeAlarmsFromRecipientList (Integer.parseInt(alarmIds[i]), user.getUserId());
                	info.put ("Selected Notifications/Warnings are removed from Recipient's list", null);
					request.setAttribute (SessionKeys.INFO_MESSAGES, info);
				}
				catch ( ScalarException se ) 
				{
					se.getRootCause().printStackTrace();
                	errors.put ("Internal Server Error:", "Could not remove the alarms/warnings from Recipient list");
					request.setAttribute (SessionKeys.ERROR_MESSAGES, errors);
				}
			}
			// This is commented by ravikanth on 30 July 03.	to facilitate confirm delete message	
			/*
				Enumeration params = request.getParameterNames();
				String name = null;
				String value = null;
				int alarmId = -1;
    
				while (params.hasMoreElements()) {
					name = (String) params.nextElement();
        
					if (name.startsWith ("select_")) {
						try {
							alarmId = Integer.parseInt ( name.substring ( name.indexOf ('_') + 1) );
						}
						catch (NumberFormatException nfe) {
							// invalid alarmId
							// dont remove -- ignore
						}
            
						try {
							AlarmDAO.removeAlarmsFromRecipientList (alarmId, user.getUserId());
                
							HashMap info = new HashMap();
							info.put ("Selected Notifications/Warnings are removed from Recipient's list", null);
							request.setAttribute (SessionKeys.INFO_MESSAGES, info);
						}
						catch (ScalarException se) {
							se.getRootCause().printStackTrace();
                
							HashMap errors = new HashMap();
							errors.put ("Internal Server Error:", "Could not remove the alarms/warnings from Recipient list");
							request.setAttribute (SessionKeys.ERROR_MESSAGES, errors);
						}
					}
				}
			  */ 
		}
    
        return (new ActionForward (ConfigManager.getIndexPageByGroupName (user.getGroupName())));
    }
}